﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using AcctrueWMS.Foundation.Web;

namespace AcctrueWMS.Foundation.Data
{
    //生成wbs码
    public class GeneratorWbsFactory
    {
        private IDataModelContext context = Runtime.Context;
        public GeneratorWbsFactory()
        {
            context = Runtime.Context;
        }

        public string GenerateWbsCode(string id, DataModel model, string condition)
        {
            string newWbscode = string.Empty;

            //string id_wbs = model[model.WbsCodeColumn].Value.ToString();
            Regex RegWbs = new Regex("(((?!{).)+)?({(?<expr>.*?)})*");
            System.Collections.ArrayList regWbsContent = new System.Collections.ArrayList();
            string wbsReglar = model.WbsCodeGenType.ToString();
            if (!string.IsNullOrEmpty(wbsReglar))
            {
                if (RegWbs.IsMatch(model.WbsCodeGenType))
                {
                    for (int i = 0; i < RegWbs.Match(wbsReglar).Groups["expr"].Captures.Count; i++)
                    {
                        regWbsContent.Add(RegWbs.Match(wbsReglar).Groups["expr"].Captures[i].Value.ToString());
                    }
                }
            }

            if ((string.IsNullOrEmpty(id) || id == "-1") && string.IsNullOrEmpty(condition))//没有id而且没有传递 condition :主要是传递pwbs
            {
                DataModel tesModel = new DataModel(context, model.Name);//model;
                string testQuery =tesModel.WbsCodeColumn + " not like '%.%'";
                tesModel.Select(testQuery);
                if (tesModel.Rows.Count > 0)//生成一层节点
                {
                    //返回一级节点+1；
                    ArrayList arr = new ArrayList();
                    for (int i = 0; i < tesModel.Rows.Count; i++)
                    {
                        arr.Add(tesModel.Rows[i][tesModel.WbsCodeColumn].Value.ToString());
                    }
                    int intNewWbs = GetMaxSectionWbs(arr) + 1;
                    newWbscode = FormatSectionWbsCode(intNewWbs, Convert.ToInt32(regWbsContent[0]));
                }
                else//首次生成节点//节点为0，并按要求格式化
                {
                    newWbscode = FormatSectionWbsCode(0, Convert.ToInt32(regWbsContent[0]));
                }
            }
            else//id不为空有查询条件
            {
                if (condition.ToLower().Contains("wbs"))
                {
                    string[] conditonArr = condition.Replace("'", "").Trim().Split('=');
                    string wbsQuery =condition;
                    DataModel wbsModel = new DataModel(context, model.Name);
                    wbsModel.Select(wbsQuery);
                    string wbsId = wbsModel.Rows[0][model.KeyColumnName].Value.ToString();
                    if (string.IsNullOrEmpty(newWbscode))
                    {
                        newWbscode = GenerateWbsCode(wbsId, model, "");
                    }
                    
                }
                else//传递id
                {
                    newWbscode = NewWbsCode(id, model, newWbscode, regWbsContent);
                }
            }
            return newWbscode;
        }

        private string NewWbsCode(string id, DataModel model, string newWbscode, ArrayList regWbsContent)
        {
            DataModel ChildModel = new DataModel(context, model.Name); //model;
            string QueryStr =ChildModel.KeyColumnName + "='" + id + "'";
            ChildModel.Single(QueryStr);
            string id_wbs = ChildModel.Rows[0][ChildModel.WbsCodeColumn].Value.ToString();
            string selectChilds =ChildModel.WbsCodeColumn.ToString() + " like '" + id_wbs + ".%'";//根据wbs选择当前节点的子节点
            DataModel wbsChildContent = ChildModel.Select(selectChilds);

            ArrayList wbsColumnRows = new ArrayList();//存储wbs列内容
            for (int i = 0; i < wbsChildContent.Rows.Count; i++)
            {
                wbsColumnRows.Add(wbsChildContent.Rows[i][ChildModel.WbsCodeColumn].Value);
            }

            if (wbsColumnRows.Count > 0)
            {
                //筛选符合条件的一级节点,去掉不符合条件的wbscode
                for (int i = 0; i < wbsColumnRows.Count; i++)
                {
                    string temp = wbsColumnRows[i].ToString();
                    string[] wbsDotLen = id_wbs.Split('.');
                    if (temp.Split('.').Length != id_wbs.Split('.').Length + 1)
                    {
                        wbsColumnRows.Remove(wbsColumnRows[i]);
                    }
                }
                if (wbsColumnRows.Count > 0)
                {
                    int maxTempwbs = GetMaxSectionWbs(wbsColumnRows) + 1;//+1
                    int confSectionLen = Convert.ToInt32(regWbsContent[id_wbs.Split('.').Length + 1].ToString());
                    newWbscode = FormatSectionWbsCode(maxTempwbs, confSectionLen);
                }
                else//没有子节点,新加第一个子节点
                {
                    newWbscode = FormatSectionWbsCode(1, id_wbs.Split('.').Length + 1);
                }
            }
            else//没有子节点新增
            {
                newWbscode = FormatSectionWbsCode(1, id_wbs.Split('.').Length + 1);
            }
            return id_wbs + "." + newWbscode;//父+新子
        }
        /// <summary>
        ///  生成wbs片段
        /// </summary>
        /// <param name="wbs"></param>
        /// <param name="formatLength"></param>
        /// <returns></returns>
        public string FormatSectionWbsCode(int sectionWbs, int formatLength)
        {
            string partWbs = sectionWbs.ToString();
            if (partWbs.Length > formatLength)
            {
                //"异常";超出配置范围
            }
            for (int i = 0; i < formatLength - partWbs.Length; i++)
            {
                partWbs = "0" + partWbs;
            }
            return partWbs;
        }

        public int GetMaxSectionWbs(ArrayList list)
        {
            int maxSectionWbs = 0;
            for (int i = 0; i < list.Count; i++)
            {
                if (Convert.ToInt32(list[i].ToString().Split('.').Last()) > maxSectionWbs)
                {
                    maxSectionWbs = Convert.ToInt32(list[i].ToString().Split('.').Last());
                }
            }
            return maxSectionWbs;
        }




        #region  //手工---验证wbsCode---并按配置格式化wbs
        ///// <summary>
        ///// 验证wbs是否存在并返回符合格式的wbscode
        ///// </summary>
        ///// <param name="modelName">modelname</param>
        ///// <param name="wbs">wbscode</param>
        ///// <param name="opt">state</param>
        ///// <returns>format wbs code </returns>
        //[WebMethod]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        //public string ValidateNewWbs(string modelName, string wbs, string opt)
        //{
        //    bool volidated;//格式化是否成功
        //    string sysFormatWbscode = string.Empty;//格式后的wbs
        //    DataModel model = new DataModel(context, modelName);
        //    FromatWbsCode(out volidated, out sysFormatWbscode, wbs, model.WbsCodeGenType.ToString());
        //    if (volidated)
        //    {
        //        model.Select(" where " + model.WbsCodeColumn + " = '" + sysFormatWbscode + "'");

        //        if (opt == "1" && model.Rows.Count > 0)
        //        {
        //            return "false2";
        //        }
        //        else
        //        {
        //            return sysFormatWbscode;
        //        }
        //    }
        //    else
        //    {
        //        return "false";
        //    }
        //}

        ///// <summary>
        ///// 根据配置格式化wbs编码
        ///// </summary>
        ///// <param name="wbscode"></param>
        //private void FromatWbsCode(out bool volidated, out string wbscode, string wbs, string confWbs)
        //{
        //    volidated = true;
        //    Regex RegWbs = new Regex("(((?!{).)+)?({(?<expr>.*?)})*");
        //    System.Collections.ArrayList setWbs = new System.Collections.ArrayList();
        //    if (RegWbs.IsMatch(confWbs))
        //    {
        //        for (int i = 0; i < RegWbs.Match(confWbs).Groups["expr"].Captures.Count; i++)
        //        {
        //            setWbs.Add(RegWbs.Match(confWbs).Groups["expr"].Captures[i].Value.ToString());
        //        }
        //    }
        //    string[] wbsNode = wbs.Split('.');
        //    for (int i = 0; i < wbsNode.Length; i++)
        //    {
        //        if (wbsNode[i].Length < Convert.ToInt32(setWbs[i].ToString()))
        //        {
        //            wbsNode[i] = FillWbsCode(wbsNode[i], Convert.ToInt32(setWbs[i].ToString()));
        //        }
        //        else if (wbsNode[i].Length > Convert.ToInt32(setWbs[i].ToString()))
        //        {
        //            volidated = false;//格式不正确  /某位数超出配置
        //            break;
        //        }
        //    }
        //    wbscode = string.Join(".", wbsNode);

        //}

        ///// <summary>
        ///// 填充缺位wbs片段
        ///// </summary>
        ///// <param name="wbs"></param>
        ///// <param name="formatLength"></param>
        ///// <returns></returns>
        //public string FillWbsCode(string wbs, int formatLength)
        //{
        //    string newWbs = string.Empty;
        //    for (int i = 0; i < formatLength - wbs.Length; i++)
        //    {
        //        newWbs = "0" + wbs;
        //    }
        //    return newWbs;
        //}
        #endregion
    }
}
